﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;

namespace CodeGenerator
{
	[Serializable]
	public class ProjectSetting
	{
		public string ProjectName
		{
			get; set;
		}

		public string ConnectionString
		{
			get; set;
		}

		public string CodePath
		{
			get; set;
		}

		public string DllPath
		{
			get; set;
		}

		public string NameSpace
		{
			get; set;
		}

		public bool HasSerializable //WebApi的自动序列化，如果类有SerializableAttribute，会导致序列化后的字段有后缀
		{
			get; set;
		}

		public bool Ybs //药博士数据库的字段说明从特定表取值
		{
			get; set;
		}

		private static readonly string FileName = Path.Combine(Application.StartupPath, "ProjectSetting.cfg");

		public static List<ProjectSetting> Load()
		{
			if (!File.Exists(FileName))
			{
				return new List<ProjectSetting>();
			}
			return XmlDeserializeList<ProjectSetting>(FileName);
		}

		public static void Save(List<ProjectSetting> settingList)
		{
			XmlSerializeList<ProjectSetting>(settingList, FileName);
		}

		public static void XmlSerializeList<T>(List<T> list, string filename)
		{
			XmlDocument xd = new XmlDocument();
			using (StringWriter sw = new StringWriter())
			{
				XmlSerializer xz = new XmlSerializer(list.GetType());
				xz.Serialize(sw, list);
				xd.LoadXml(sw.ToString());
				xd.Save(filename);
			}
		}

		public static List<T> XmlDeserializeList<T>(string fileName)
		{
			List<T> list = new List<T>();
			using (XmlReader reader = XmlReader.Create(fileName))
			{
				XmlSerializer xz = new XmlSerializer(list.GetType());
				list = (List<T>)xz.Deserialize(reader);
				return list;
			}
		}
	}
}
